package cn.itcast.bos.service.base.impl;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.AreaService;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class AreaServiceImpl implements AreaService {
    //注入dao
    @Autowired
    private AreaRepository areaRepository;
    @Override
    public void batchImport(File file) {
        //编写解析编码逻辑
        //基于.xml
        //工作部，
        try {
            //1. 加载excel文件对象
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
            //2.读取一个sheet
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
            List<Area> list =new ArrayList<Area>();
            //3. 读取sheet的每一行
            for (Row row : hssfSheet) {
                if (row.getRowNum() == 0) continue;//跳过第一行
                //编号，省份，城市，区域，邮编
                Area area = new Area();
                area.setId(row.getCell(0).getStringCellValue());
                area.setProvince(row.getCell(1).getStringCellValue());
                area.setCity(row.getCell(2).getStringCellValue());
                area.setDistrict(row.getCell(3).getStringCellValue());
                area.setPostcode(row.getCell(4).getStringCellValue());
                list.add(area);

                System.out.println("添加区域"+area);
            }

            areaRepository.save(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveBatch(List<Area> areas) {

    }

    @Override
    public Page<Area> findPageData(Specification<Area> specification, Pageable pageable) {
         return   areaRepository.findAll(specification,pageable);
    }
}
